from datetime import datetime

from flask import Blueprint, render_template, request, session
from flask_login import login_required

from apps.forms.system_log_form import QuerySystemLogForm
from rules.system_log_rule import search_system_log_with_page

system_log = Blueprint('system_log', __name__, url_prefix='/system_log')
ACTIVE = 'system'
ACTIVE_ITEM = 'system_log'
SEARCH_PAGE = 'system_log_page'


@system_log.route('/page', methods=['GET', 'POST'])
@login_required
def page():
    form = QuerySystemLogForm()
    last_search = session.get('last_search')
    page_index = 1
    module = ''
    operator = ''
    create_time_start = ''
    create_time_end = ''

    if request.method == 'GET':
        if last_search and last_search.get('search_page', '') == SEARCH_PAGE:
            # page_index = last_search.get('page_index', 1)
            if last_search.get('search_data'):
                module = last_search.get('search_data').get('module', '')
                operator = last_search.get('search_data').get('operator', '')
                create_time_start = last_search.get('search_data').get('create_time_start', '')
                create_time_end = last_search.get('search_data').get('create_time_end', '')

        page_index = request.args.get('page', page_index, type=int)

        module = request.args.get('module', module)
        operator = request.args.get('operator', operator)
        create_time_start = request.args.get('create_time_start', create_time_start)
        create_time_end = request.args.get('create_time_end', create_time_end)

        form.module.data = module
        form.operator.data = operator
        form.create_time_start.data = datetime.strptime(create_time_start, '%Y/%m/%d') if create_time_start else None
        form.create_time_end.data = datetime.strptime(create_time_end, '%Y/%m/%d') if create_time_end else None

    else:
        page_index = 1
        if form.module.data:
            module = form.module.data

        if form.operator.data:
            operator = form.operator.data

        if form.create_time_start.data:
            create_time_start = form.create_time_start.data.strftime("%Y/%m/%d")

        if form.create_time_end.data:
            create_time_end = form.create_time_end.data.strftime("%Y/%m/%d")

    search_data = dict(module=module, operator=operator, create_time_start=create_time_start,
                       create_time_end=create_time_end)
    last_search = dict(search_page=SEARCH_PAGE, page_index=page_index, search_data=search_data)
    session['last_search'] = last_search

    pagination = search_system_log_with_page(page_index, search_data)
    return render_template('system_log/page.html', pagination=pagination, form=form, active=ACTIVE,
                           active_item=ACTIVE_ITEM)
